import { NameSpace } from 'utils/index';
import exceed from 'utils/apimap';
import { Message } from '@teamix/ui';
import utils from 'utils';
import intl from '../../../locale';

const ns = NameSpace('tbProjectRepos');
const { organization } = window.FORCE;
const tbProjectId = utils.getUrlSearchParam('projectId');

export const CHANGE_SEARCH = ns('CHANGE_SEARCH');
export const GET_ALL_GROUPS = ns('GET_ALL_GROUPS');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RECEIVE_REPO_SETTING = ns('RECEIVE_REPO_SETTING');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function getProjects(page) {
  return (dispatch, getState) => {
    const { projects, projectListLoaded } = getState();

    exceed
      .fetch({
        api: 'tbProject.linkedList',
        params: {
          tbProjectId,
        },
      })
      .then((result) => {
        const data = result.slice(1);
        const total = result[0].amount;
        const curProjects = page === 1 ? data : [...projects, ...data];
        updateData({
          currentPage: page,
          projects: curProjects,
          total,
          projectListLoaded: true,
        })(dispatch);
      })
      .catch((err) => {
        if (!projectListLoaded) {
          updateData({
            projectListLoaded: true,
          })(dispatch);
        }
        console.error(err);
      });
  };
}

// 查询企业设置
export function getRepoSettingData() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'organization.repo.setting.get',
        params: {
          org_id: organization.id,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_REPO_SETTING,
          data: result,
        });
      });
  };
}

// 取消关联 DELETE /api/v4/tbproject/{tbProjectId}/repos/{projectId}
export function unlinkProject(projectId) {
  return (dispatch, getState) => {
    const { projects, total } = getState();
    const unlinkPromise = new Promise((resolve, reject) => {
      exceed
        .fetch({
          api: 'tbProject.unlink',
          params: {
            tbProjectId,
            projectId,
          },
        })
        .then((result) => {
          resolve(result);
        })
        .fail((err) => {
          reject(err);
        });
    });
    unlinkPromise
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.tb-project-repos.actions.TheAssociationIsCanceled',
            defaultMessage: '取消关联成功',
          }),
        });

        updateData({
          projects: projects.filter((item) => {
            return item.id !== projectId;
          }),
          total: total - 1,
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
      });
  };
}

// 获取tbproject info
export function getTbProjectInfo() {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'tbProject.projectInfo',
        params: {
          tbProjectId,
        },
      })
      .then((result) => {
        const data = result.result || {};
        updateData({
          tbProjectName: data.name || '',
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
      });
  };
}
